import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

// API基础URL
const NODE_API_BASE_URL = import.meta.env.VITE_NODE_API_BASE_URL;

// 创建axios实例
const request = axios.create({
  baseURL: NODE_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  paramsSerializer: {
    indexes: null
  }
});

// 检查token是否过期
const isTokenExpired = (token: string): boolean => {
  if (!token) return true;
  
  try {
    // JWT token格式为: header.payload.signature
    const base64Payload = token.split('.')[1];
    const payload = JSON.parse(atob(base64Payload));
    
    // 检查exp字段 (过期时间，以秒为单位的时间戳)
    return payload.exp ? payload.exp * 1000 < Date.now() : true;
  } catch (error) {
    console.error('Token解析出错:', error);
    return true;
  }
};

// 请求拦截器 - 添加token
request.interceptors.request.use(
  async (config) => {
    const token = localStorage.getItem('visitor_token');
    const uuid = localStorage.getItem('visitor_uuid');
    
    // 如果没有token或uuid，不添加头部
    if (!token || !uuid) {
      return config;
    }
    
    // 检查token是否过期
    if (isTokenExpired(token)) {
      console.log('Token已过期，尝试重新注册');
      try {
        // 使用现有UUID重新注册
        const response = await visitorAPI.register(uuid);
        if (response.success) {
          localStorage.setItem('visitor_token', response.data.token);
          config.headers['Authorization'] = `Bearer ${response.data.token}`;
          return config;
        }
      } catch (error) {
        console.error('Token自动续期失败:', error);
        // 清除失效的token和uuid
        localStorage.removeItem('visitor_token');
        localStorage.removeItem('visitor_uuid');
        // 可以在此处添加重定向到登录页面的逻辑
        window.location.href = '/';
      }
    } else {
      // Token有效，正常添加到请求头
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
request.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 处理401和403等授权错误
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      console.error('授权失败:', error.response.data);
      // 清除失效的token和uuid
      localStorage.removeItem('visitor_token');
      localStorage.removeItem('visitor_uuid');
      // 重定向到首页
      window.location.href = '/';
    }
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);


// 访客API
const visitorAPI = {
  // 访客注册
  register: async (uuid: string) => {
    try {
      const response = await request.post('/api/visitor/register', { uuid });
      return response.data;
    } catch (error) {
      console.error('访客注册失败:', error);
      throw error;
    }
  },
  
  // 检查访客认证状态
  checkAuth: () => {
    const uuid = localStorage.getItem('visitor_uuid');
    const token = localStorage.getItem('visitor_token');
    
    if (!uuid || !token) {
      return false;
    }
    
    return !isTokenExpired(token);
  },
  
  // 生成新的UUID
  generateUUID: () => {
    return uuidv4();
  }
};

export { request, visitorAPI }; 